package com.diudiutechnology.www.yadiudiu.yadiudiu.mine.MyActivity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Point;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.UiSettings;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.diudiutechnology.www.yadiudiu.R;
import com.diudiutechnology.www.yadiudiu.util.utils.Constant;
import com.diudiutechnology.www.yadiudiu.yadiudiu.main.MyApplication;
import com.diudiutechnology.www.yadiudiu.yadiudiu.mine.MyAdapter.SelectTheAddressActivityAdapter;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by Administrator on 2017/8/23.
 * 地址选择
 * 0、添加收获地址 1、申请入驻 2、修改店铺资料 3、添加买房商品
 */

public class SelectTheAddressActivity extends Activity implements View.OnClickListener {
    @Bind(R.id.retur)
    LinearLayout retur;

    Context context;
    @Bind(R.id.search_ly)//搜索地址
            LinearLayout search_ly;

    @Bind(R.id.listview)
    ListView listview;

    SelectTheAddressActivityAdapter adapter;


    @Bind(R.id.bmapsView)//地图
    MapView bmapsView;
    BaiduMap mBaiduMap;
    BitmapDescriptor mCurrentMarker;

    // MapView中央对于的屏幕坐标
    Point mCenterPoint = null;
    // 地理编码
    GeoCoder mGeoCoder = null;

    List<PoiInfo> mInfoList;
    private UiSettings mUiSettings;
  //  private MyProgressDialog mDialog;
    String pos="0";//0、添加地址 1、申请入驻 2、修改店铺资料
    String province="";//省份名称
    String city="";//城市名称
    String district="";//区县名称
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_the_address);
        ButterKnife.bind(this);
        context = this;
        initView();
    }

    private void initView() {
        retur.setOnClickListener(this);
        search_ly.setOnClickListener(this);
        if (getIntent()!=null){
            pos=getIntent().getStringExtra("pos");
        }
        // 初始化POI信息列表
        mInfoList = new ArrayList<PoiInfo>();
        adapter=new SelectTheAddressActivityAdapter(context);
        listview.setAdapter(adapter);
        mBaiduMap = bmapsView.getMap();
        LatLng latLng = new LatLng(MyApplication.getInstance().getLatitude(), MyApplication.getInstance().getLongitude());
        mCurrentMarker = BitmapDescriptorFactory
                .fromResource(R.mipmap.label_delete);
        //构建MarkerOption，用于在地图上添加Marker
        OverlayOptions option = new MarkerOptions()
                .position(latLng)
                .icon(mCurrentMarker);
        //在地图上添加Marker，并显示
        mBaiduMap.addOverlay(option);
        MapStatus.Builder builder = new MapStatus.Builder();
        builder.target(latLng).zoom(21);
        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
        //地图主控件
        mUiSettings = mBaiduMap.getUiSettings();
        mUiSettings.setCompassEnabled(false);
        mUiSettings.setOverlookingGesturesEnabled(false);
        // 不显示地图上比例尺
        bmapsView.showScaleControl(false);
        // 不显示地图缩放控件（按钮控制栏）
        bmapsView.showZoomControls(false);

        // 初始化当前MapView中心屏幕坐标，初始化当前地理坐标
         mCenterPoint = mBaiduMap.getMapStatus().targetScreen;
        mBaiduMap.setOnMapTouchListener(touchListener);


     //   mDialog =new MyProgressDialog(context);
        // 地理编码
        mGeoCoder = GeoCoder.newInstance();
        mGeoCoder.setOnGetGeoCodeResultListener(GeoListener);
        mGeoCoder.reverseGeoCode((new ReverseGeoCodeOption())
                .location(latLng));
        listview.setOnItemClickListener(clicklist);
    }
AdapterView.OnItemClickListener clicklist=new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        PoiInfo poiInfo = mInfoList.get(i);
        LatLng location = poiInfo.location;
        Intent intent=new Intent();
        intent.putExtra("province",province);
        intent.putExtra("city",city);
        intent.putExtra("district",district);
        intent.putExtra("latitude",location.latitude+"");
        intent.putExtra("longitude",location.longitude+"");
        intent.putExtra("name",poiInfo.name);
        intent.putExtra("address",poiInfo.address);
        if (pos.equals("0")){
            setResult(Constant.ADDRESS,intent);
        }else   if (pos.equals("1")){
            setResult(Constant.APPLICATION,intent);
        }else   if (pos.equals("2")){
            setResult(Constant.MODIFICATION,intent);
        }else   if (pos.equals("3")){
            setResult(Constant.ADDADDRESSHOUSE,intent);
        }else   if (pos.equals("4")){
            setResult(Constant.ADDADDRESSCARIMG,intent);
        }

        finish();
    }
};
    // 地图触摸事件监听器
    BaiduMap.OnMapTouchListener touchListener = new BaiduMap.OnMapTouchListener() {
        @Override
        public void onTouch(MotionEvent event) {
            // TODO Auto-generated method stub
            if (event.getAction() == MotionEvent.ACTION_UP) {

                if (mCenterPoint == null) {
                    return;
                }

                // 获取当前MapView中心屏幕坐标相应的地理坐标
                LatLng currentLatLng;
                currentLatLng = mBaiduMap.getProjection().fromScreenLocation(
                        mCenterPoint);
                System.out.println("----" + mCenterPoint.x);
                System.out.println("----" + currentLatLng.latitude);
                // 发起反地理编码检索
                mGeoCoder.reverseGeoCode((new ReverseGeoCodeOption())
                        .location(currentLatLng));
           //     mDialog =new MyProgressDialog(context);

            }
        }
    };

    // 地理编码监听器
    OnGetGeoCoderResultListener GeoListener = new OnGetGeoCoderResultListener() {
        public void onGetGeoCodeResult(GeoCodeResult result) {
            if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                // 没有检索到结果
            }
            // 获取地理编码结果
        }

        @Override
        public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
            if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                // 没有找到检索结果
            }
            // 获取反向地理编码结果
            else {
                // 当前位置信息
//                mCurentInfo = new PoiInfo();
//                mCurentInfo.address = result.getAddress();
//                mCurentInfo.location = result.getLocation();
//                mCurentInfo.name = "[位置]";
                ReverseGeoCodeResult.AddressComponent addressDetail = result.getAddressDetail();
                 province = addressDetail.province;
                city = addressDetail.city;
                district= addressDetail.district;
                mInfoList.clear();
//                mInfoList.add(mCurentInfo);
                System.out.println("");
                // 将周边信息增加表
                if (result.getPoiList() != null) {
                    mInfoList.addAll(result.getPoiList());
                }
                // 通知适配数据已改变
                adapter.addItem(mInfoList);
//                if (mDialog!=null){
//                    mDialog.dismiss();
//                }

            }
        }
    };

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.retur:
                finish();
                break;
            case R.id.search_ly:
                Intent intent = new Intent(context, AddressSearchActivity.class);
                intent.putExtra("pos","0");
                startActivityForResult(intent, Constant.SELECT);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==Constant.SELECT){
               String longitude =data.getStringExtra("longitude");//   经度
                String  latitude  =data.getStringExtra("latitude");//  纬度
                LatLng latLng = new LatLng(Double.valueOf(latitude),Double.valueOf(longitude));
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(latLng).zoom(21);
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
                mGeoCoder.reverseGeoCode((new ReverseGeoCodeOption())
                    .location(latLng));
        }
    }

    @Override
    protected void onPause() {
        bmapsView.onPause();
        super.onPause();
    }

    @Override
    protected void onResume() {
        bmapsView.onResume();
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        bmapsView.onDestroy();
        super.onDestroy();
    }
}

